package freedom.sample.poi;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Bookmark;
import org.apache.poi.hwpf.usermodel.Bookmarks;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.xmlbeans.XmlException;

/**
 * @author charlie
 *
 */
public class ReadWord {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String file = "合同文本-副本.doc";
		String type = "2003";
		try {
			read(file, type);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void read(String file, String type)
			throws FileNotFoundException, IOException, XmlException, OpenXML4JException {
		if ("2003".equals(type)) {
			InputStream is = new FileInputStream(new File(file));
			HWPFDocument doc = new HWPFDocument(is);

			Bookmarks bookmarks = doc.getBookmarks();
			int count = bookmarks.getBookmarksCount();
			int[][] arr = new int[count][2];
			
			for (int i = 0, j = bookmarks.getBookmarksCount(); i < j; i++) {
				Bookmark bookmark = bookmarks.getBookmark(i);
				System.out.println(bookmark);
				arr[i][0] = bookmark.getStart();
				arr[i][1] = bookmark.getEnd();
				
			}
			/*Range r = doc.getRange();

			for (int x = 0; x < r.numSections(); x++) {

				Section s = r.getSection(x);

				for (int y = 0; y < s.numParagraphs(); y++) {

					Paragraph p = s.getParagraph(y);

					for (int z = 0; z < p.numCharacterRuns(); z++) {

						CharacterRun run = p.getCharacterRun(z);

						// 字符串文本

						String text = run.text();
						System.out.println(text);
						
					}

				}

			}*/
			Range range = doc.getRange();
			String newFileName = "x.doc";
			File newFile = new File(newFileName);
			doc.write(newFile);

			StringBuilder sb = doc.getText();
			for (int i = 0; i < sb.length(); i++) {
			}
			
			doc.close();
			is.close();

			/*
			 * office95
			 * 
			 * WordExtractor ex = new WordExtractor(is); String text2003 =
			 * ex.getText(); ex.close(); System.out.println(text2003);
			 */
			
			

		} else if ("2007".equals(type)) {
			OPCPackage opcPackage = POIXMLDocument.openPackage(file);
			POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
			String text2007 = extractor.getText();
			extractor.close();
			opcPackage.close();
			System.out.println(text2007);
			

		}
	}
	

}
